const app = getApp();
let lat1 = ''
let lng1 = ''
let lat2 = ''
let lng2 = ''
let keyWord = ''
let count = 20
let resCount = 20
Page({
  data: {
    shops: [],
    TabCur: 0,
    scrollLeft: 0,
    Tab: ['全部商家', '附近商家', '福利商家'],
    currentIndex: 0,
    latitude: undefined,
    longitude: undefined,
    shopIsFuli: true,
    keyWord:'',
    shopAd:null
  },
  // 排序
  paiXu() {
    let arr = this.data.shops
    // console.log(arr, 'paixu----------------')
    arr.sort(this.compare("jisuan"));    
     
    for(var i = 0;i<arr.length; i++){  
    // console.log(arr[i].jisuan, 'paixu+++++++++++++++++')
    // console.log(arr, 'paixu+++++++++++++++++')
    }  
    // console.log(arr, 'paixu+++++++++++++++++')
    this.setData({
      shops:arr
    })

  },
    // 排序函数
 compare(name){  
    return function(o, p){  
      var a, b;  
      if (typeof o === "object" && typeof p === "object" && o && p) {  
        a = o[name];  
        b = p[name];  
        if (a === b) {  
          return 0;  
        }  
        if (typeof a === typeof b) {  
          return a < b ? -1 : 1;  
        }  
        return typeof a < typeof b ? -1 : 1;  
      }  
      else {  
        throw ("error");  
      }  
    }  
   },  
  // 页面距离展示
  // 1.进入页面先获取用户位置授权
  // 授权成功  保存位置
  // 失败 重新发起
  getUserLocation() {
    wx.getLocation({
        type: 'wgs84',
      })
      .then(res => {
        lat1 = res.latitude
        lng1 = res.longitude
        // 成功获取位置后再计算商家与自己的距离再次渲染距离到页面
      })
  },
  // 计算两位置之间的距离
  getDistance(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = 25.526473 || 0;
    lng2 = 103.792162 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    let jvli = (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0) / 1000
    // console.log("距离为", jvli, 'km')
    return jvli
  },
  onLoad() {
    this.setData({
      shopAd:app.globalData.ads.shopAd
    })
    // 获取用户位置信息
    this.getUserLocation()
    // 页面加载 去数据库请求商家数据 用云函数
    // console.log(keyWord,"打印key")
    this.getShop()
  },
  // 请求商家数据
  getShop(start = 0) {
    wx.showLoading({
      title: '拼命加载中...',
    })
    wx.cloud.callFunction({
        name: 'getShop',
        data: {
          tag: 'all',
          keyWord,
          start,
          count,
        }
      })
      .then(res => {
        let index = 0
        let newList = []
        res.result.forEach(item => {
          // console.log(item.address.latitude,item.address.longitude)
          lat1 = item.address.latitude
          lng1 = item.address.longitude
          let jvli = {
            jisuan: ''
          }
          jvli.jisuan = this.getDistance(lat1, lng1, lat2, lng2)
          index += 1
          let newObj = {
            ...res.result[index - 1],
            ...jvli
          }
          newList.push(newObj)
        });
        this.setData({
          shops: this.data.shops.concat(newList)
        })
        wx.stopPullDownRefresh()
        wx.hideLoading()
        this.setData({
          keyWord:''
        })
        // console.log(res.result.length, "获取数据成功回调")
        resCount = res.result.length
        if (resCount < count) {
          wx.showToast({
            icon: 'none',
            title: '没有更多数据了',
          })
          return;
        }
      })
  },
  // 搜索
  searchKey(e) {
    keyWord = e.detail.value
  },
  sendSearch() {
    // 判断用户输入的值是否为空
    if (keyWord.trim() == '') {
      wx.showToast({
        icon: 'error',
        title: '搜索内容不能为空',
      })
      return;
    }
    // 先清空页面原来的数据，
    this.setData({
      shops: []
    })
    // 调用数据库查询方法,从第0条数据开始检索
    this.getShop(0)
    // 查询成功要在getShop方法内清空keyWord
  },
  // 跳转到商家详情页
  getShopDetail(e) {
    let id = e.currentTarget.dataset.id
    let name = e.currentTarget.dataset.name
    wx.navigateTo({
      url: '/pages/my-shop/my-shop?id=' + id + '&name=' + name,
    })
  },
  onShow() {
    this.tabBar()
    // this.getUserLocation()
  },
  tabBar() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  },

  tabSelect(e) {
    let current = e.currentTarget.dataset.id
    if (current == 0) {
      this.setData({
        currentIndex: 0
      })
      this.setData({
        shops:[]
      })
      keyWord=''
      this.getShop()
    } else if (current == 1) {
      this.setData({
        currentIndex: 1
      })

      
      this.paiXu()
    } else {
      this.setData({
        currentIndex: 2,
        shopIsFuli: false
      })
      this.setData({
        shops:[]
      })
      keyWord=''
      this.getShop()
      
    }
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (resCount < count) {
      wx.showToast({
        icon: 'none',
        title: '没有更多数据了',
      })
      return;
    }
    this.getShop(this.data.shops.length)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      shops: []
    })
    this.getShop(0)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return {
      title: '商家福利大派送',
      path: '/pages/shop/shop',
      imageUrl: '/images/fuli.png'
    }
  },
  onShareTimeline: function (res) {
    console.log(res)
    return {
      title: '商家福利大派送',
      query: "/pages/shop/shop", //JSON.stringify(query.data);
      imageUrl: '/images/fuli.png',
      success: function (res) {
        // 转发成功
      }
    }
  }
})